/*
 *    Copyright (c) 2018-2025, daoism All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: daoism
 */
package com.mkh.st.admin.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mkh.st.admin.api.dto.StSnSaveDTO;
import com.mkh.st.admin.api.entity.StSn;
import com.mkh.st.admin.api.vo.SnListVO;
import com.mkh.st.admin.api.vo.SnPageVO;
import com.mkh.st.admin.mapper.StSnMapper;
import com.mkh.st.admin.service.StSnService;
import com.mkh.st.common.core.constant.CommonConstants;
import com.mkh.st.common.core.exception.BizException;
import com.mkh.st.common.core.util.R;
import com.mkh.st.common.data.datascope.RedisUtil;
import com.mkh.st.common.security.service.DaoismUser;
import com.mkh.st.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * 编码规则表
 *
 * @author daoism code generator
 * @date 2021-07-29 19:52:35
 */
@Service
@AllArgsConstructor
public class StSnServiceImpl extends ServiceImpl<StSnMapper, StSn> implements StSnService {

	private final StSnMapper stSnMapper;
	private final String squence="SQ:";

	@Override
	public IPage<SnPageVO> snPage(Page page, Long id) {
		IPage<StSn> iPage=stSnMapper.selectPage(page, Wrappers.<StSn>lambdaQuery().eq((ObjectUtil.isNotNull(id)),StSn::getId,id)
				.eq(StSn::getTenantId,SecurityUtils.getUser().getTenantId()));
		IPage<SnPageVO> pageInfo=new Page<>();
		if(CollectionUtil.isEmpty(iPage.getRecords())){
			return pageInfo;
		}
		List<SnPageVO> list=new ArrayList<>();
		iPage.getRecords().forEach(item ->{
			SnPageVO vo= BeanUtil.toBean(item,SnPageVO.class);
			// 1/CC 获取当前值
			Object value= RedisUtil.get(squence+item.getTenantId()+ CommonConstants.SPLIT+item.getCode());
			if(ObjectUtil.isNotNull(value)){
				vo.setNowSerialNumber(Integer.valueOf(value.toString()));
			}else {
				vo.setNowSerialNumber(CommonConstants.ZERO);
			}
			list.add(vo);
		});
		pageInfo.setRecords(list).setTotal(iPage.getTotal()).setSize(iPage.getSize()).setCurrent(iPage.getCurrent()).setPages(iPage.getPages());
		return pageInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R<Boolean> saveSn(StSnSaveDTO dto) {
		DaoismUser user = SecurityUtils.getUser();
		StSn stSn=BeanUtil.toBean(dto,StSn.class);
		stSn.setTenantId(user.getTenantId());
		stSn.setUpdateBy(user.getName()).setUpdateId(user.getId()).setUpdateTime(LocalDateTime.now());
		RedisUtil.set(squence+user.getTenantId()+ CommonConstants.SPLIT+dto.getCode(),dto.getNowSerialNumber());
		if(setKey(stSn,dto.getNowSerialNumber().toString())){
			return R.ok(updateById(stSn));
		}
		return R.ok(Boolean.FALSE);
	}

    @Override
    public List<SnListVO> snList() {
		List<StSn> stSns=stSnMapper.selectList(Wrappers.<StSn>lambdaQuery()
				.eq(StSn::getTenantId,SecurityUtils.getUser().getTenantId()));
		List<SnListVO> list=new ArrayList<>();
		stSns.forEach(item ->{
			SnListVO vo=BeanUtil.toBean(item,SnListVO.class);
			list.add(vo);
		});
        return list;
    }

	@Override
    public String getSequenceCode(String code){
		StSn stSn=stSnMapper.selectOne(Wrappers.<StSn>lambdaQuery().eq(StSn::getCode,code)
			.eq(StSn::getTenantId,SecurityUtils.getUser().getTenantId()));
		Object value= RedisUtil.get(squence+stSn.getTenantId()+ CommonConstants.SPLIT+stSn.getCode());
		String str="0";
		if(ObjectUtil.isNotNull(value)){
			Integer count=Integer.valueOf(value.toString())+1;
			str=count.toString();
		}else {
			str="1";
		}
		StringBuilder sb = new StringBuilder();
		if(StrUtil.isNotBlank(stSn.getPrefix())){
			sb.append(stSn.getPrefix());
		}
		if(StrUtil.isNotBlank(stSn.getDateFormat())){
			if("YYYYMMDD".equals(stSn.getDateFormat())){
				sb.append(DateUtil.format(LocalDateTime.now(),"yyyyMMdd"));
			}else if("YYYYMM".equals(stSn.getDateFormat())){
				sb.append(DateUtil.format(LocalDateTime.now(),"yyyyMM"));
			}else if("YYYY".equals(stSn.getDateFormat())){
				sb.append(DateUtil.format(LocalDateTime.now(),"yyyy"));
			}
		}
		sb.append(addZeroForNum(str,stSn.getSerialNumberSize()));
		if(setKey(stSn,str)){
			return sb.toString();
		}
		return null;
	}

	private Boolean setKey(StSn stSn,String count){
		if(StrUtil.isNotBlank(stSn.getDateFormat())){
			LocalDateTime beginTime=LocalDateTime.now();
			if("YYYYMMDD".equals(stSn.getDateFormat())){
				//每天清零
				LocalDateTime endTime= beginTime.withHour(23).withMinute(59).withSecond(59);
				Long expire= LocalDateTimeUtil.between(beginTime,endTime, ChronoUnit.SECONDS);
				return RedisUtil.set(squence+stSn.getTenantId()+ CommonConstants.SPLIT+stSn.getCode(),count,expire);
			}else if("YYYYMM".equals(stSn.getDateFormat())){
			//每月清零
				LocalDateTime endTime=beginTime.withDayOfMonth(beginTime.getMonth().maxLength()).withHour(23).withMinute(59).withSecond(59);
				Long expire= LocalDateTimeUtil.between(beginTime,endTime, ChronoUnit.SECONDS);
				return RedisUtil.set(squence+stSn.getTenantId()+ CommonConstants.SPLIT+stSn.getCode(),count,expire);
			}else if("YYYY".equals(stSn.getDateFormat())){
			//每年清零
				LocalDateTime endTime=beginTime.withMonth(12).withDayOfMonth(31).withHour(23).withMinute(59).withSecond(59);
				Long expire= LocalDateTimeUtil.between(beginTime,endTime, ChronoUnit.SECONDS);
				return RedisUtil.set(squence+stSn.getTenantId()+ CommonConstants.SPLIT+stSn.getCode(),count,expire);
			}
		}else {
			return RedisUtil.set(squence+stSn.getTenantId()+ CommonConstants.SPLIT+stSn.getCode(),count);
		}
		return Boolean.FALSE;
	}

	/**
	 *
	 * @param str 取的流水最大值
	 * @param strLength 流水号位数
	 * @return
	 */
	private   String addZeroForNum(String str, int strLength) {
		int strLen = str.length();
		if (strLen < strLength) {
			while (strLen < strLength) {
				StringBuffer sb = new StringBuffer();
				sb.append("0").append(str);//左补0
				str = sb.toString();
				strLen = str.length();
			}
		}else if(strLen == strLength){
			StringBuffer max = new StringBuffer("9");
			for (int i = 1; i <strLength ; i++) {
				max.append("9").append(str);//左补
			}
			Integer	maxCount=Integer.valueOf(max.toString());
			Integer	strCount=Integer.valueOf(str);
			if(strCount.compareTo(maxCount)==0){
				throw new BizException(1122,"已超最大值!");
			}
		}else {
			throw new BizException(1133,"已超最大值!");
		}
		return str;
	}
}
